package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public Result order(Map map,Integer addressId) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约时间
        String telephone = (String) map.get("telephone");//手机号
        Integer setmealId = Integer.parseInt((String) map.get("setmealId"));//套餐id
        Jedis resource = jedisPool.getResource();
        String set = resource.getSet(orderDate + ":" + telephone + ":" + setmealId, "1");
        resource.expire(orderDate + ":" + telephone + ":" + setmealId, 300);
        jedisPool.close();
        if (set != null) {
            return new Result(false, "不可以同时访问");
        }
        //找出日期是否存在预约
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查是否约满了
        int number = orderSetting.getNumber(); //总与约数
        int reservations = orderSetting.getReservations(); //已预约数
        if (number <= reservations) {//判断是否预约慢
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否存在同一天预约多次
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            //3.1不等于空证明用户已经是会员用户
            Integer memberId = member.getId();
            Order order = new Order(memberId, date, setmealId);
            //3.1.1查询该会员是否当天存在预约
            List<Order> list = orderDao.findByCondition(order);
            //如果存在返回失败 已预约提示
            if (list != null && list.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、不是会员用户自动添加为会员
            //4.1 添加会员信息
            member = new Member();
            member.setName((String) map.get("name"));//姓名
            member.setPhoneNumber(telephone);//电话
            member.setIdCard((String) map.get("idCard"));//身份证信息
            member.setSex((String) map.get("sex"));//性别
            member.setRegTime(new Date());//注册时间
            memberDao.add(member);//自动完成会员注册
        }
        //5、条件满足时为用户添加预约
        Order order = new Order();
        order.setMemberId(member.getId());//添加会员id
        order.setOrderDate(date);//添加预约时间
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(setmealId);//添加套餐id 在上面的
        orderDao.add(order);
        Map map1 = new HashMap();
        map1.put("order_id",order.getId());
        map1.put("address_id",addressId);

        orderDao.addOrderIdAndAddressId(map1);
        //增加已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());


    }

    @Override
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
         Address address = orderDao.findOrderIdByAddress(id);
         map.put("address_name",address.getName());
         map.put("address_address",address.getAddress());
         map.put("address_landmark",address.getLandmark());
         map.put("address_phone",address.getPhone());
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            try {
                map.put("orderDate",DateUtils.parseDate2String(orderDate));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
